package com.lx.ngsl.exam.autopaper.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lx.ngsl.exam.autopaper.entity.PaperEntity;
import com.lx.ngsl.exam.autopaper.entity.PaperQuestEntity;
import com.lx.ngsl.exam.autopaper.repository.AutoPaperRepository;
import com.lx.ngsl.exam.autopaper.repository.Paper_QuestRepository;
import com.lx.ngsl.exam.quest.entity.ChoiceEntity;
import com.lx.ngsl.exam.quest.entity.QuestEntity;
import com.lx.ngsl.exam.quest.repository.ChoiceRepository;
import com.lx.ngsl.exam.quest.repository.QuestRepository;

import javassist.bytecode.Descriptor.Iterator;
@Service
public class AutoPaperService {
	@Autowired
	private AutoPaperRepository repository;
	@Autowired
	private Paper_QuestRepository Questrepository;
	@Autowired
	private QuestRepository questRepository;
	@Autowired
	private ChoiceRepository choiceRepository;
	public Page<PaperEntity> paperListPage(Pageable pageable){
		Page<PaperEntity> list = repository.findAll(new Specification<PaperEntity>() {
			@Override
			public Predicate toPredicate(Root<PaperEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				
				Predicate predicate = cb.conjunction();
				List<Expression<Boolean>> expressions = predicate.getExpressions();
				expressions.add(cb.equal(root.<String> get("status"), "1"));
				return predicate;
			}
		}, pageable);

		return list;
	}
	@Transactional
	public boolean addPage(String title) {
		String uuid = UUID.randomUUID().toString();
		PaperEntity paper=new PaperEntity();
		paper.setId(uuid);
		paper.setStatus("1");
		paper.setTitle(title);
		
		List<QuestEntity> singleList=questRepository.findByType("单选题");
		List<QuestEntity> multipleList=questRepository.findByType("多选题");
		List<QuestEntity> judgeList=questRepository.findByType("判断题");
		HashSet<Integer> singleSet = randomNum(singleList.size(),40);
		HashSet<Integer> multipleSet = randomNum(multipleList.size(),20);
		HashSet<Integer> judgeSet = randomNum(judgeList.size(),40);
		paperSave(singleSet,singleList,uuid);
		paperSave(multipleSet,multipleList,uuid);
		paperSave(judgeSet,judgeList,uuid);
		byte json[]= queryPage(uuid);
		paper.setJson(json);
		repository.save(paper);
		return true;
	}
	private void paperSave(HashSet<Integer> set,List<QuestEntity> list,String paperid) {
		java.util.Iterator<Integer> it=set.iterator();
		while(it.hasNext()) {
			PaperQuestEntity quest=new PaperQuestEntity();
			String uuid = UUID.randomUUID().toString();
			quest.setId(uuid);
			quest.setPaperid(paperid);
			quest.setQuest_id(list.get(it.next()).getId());
			Questrepository.save(quest);
		}
	}
	private HashSet<Integer> randomNum(int n,int num) {
		HashSet<Integer> set=new HashSet();
		for(int i=0,ii=0;i<num;) {
			int rn=(int) (Math.random()*(n-1));
			set.add(rn);
			
			if(set.size()!=ii) {
				i++;
				ii=set.size();
			}
		}
		return set;
	}
	public void delePage(String Id) {
		Optional<PaperEntity> paper=repository.findById(Id);
		PaperEntity paperEn=paper.get();
		paperEn.setStatus("0");
		repository.save(paperEn);
	}
	@Transactional
	public byte[] queryPage(String paperid) {
		List<PaperQuestEntity> paperQuestEntity =Questrepository.findByPaperid(paperid);
		java.util.Iterator<PaperQuestEntity> itpaper = paperQuestEntity.iterator();
		JSONArray Json = new JSONArray();
		while(itpaper.hasNext()) {
			Map<String, String>  map =new HashMap();
			String answer="";
			Optional<QuestEntity> questEntity = questRepository.findById(itpaper.next().getQuest_id());
			java.util.Iterator<ChoiceEntity> choice = choiceRepository.findByQuestId(questEntity.get().getId()).iterator();
            map.put("id", questEntity.get().getId());
            map.put("q_type", questEntity.get().getType());
			map.put("title",questEntity.get().getQuest());
			while(choice.hasNext()) {
				ChoiceEntity choiceEntity =choice.next();
				String inx = choiceEntity.getInx() == null ? "T":choiceEntity.getInx();
				switch(inx) {
					case "A": map.put("optionA", choiceEntity.getContent());
					if(choiceEntity.getIsTrue().equals("1")) {
						answer+="A";
					}
					break;
					case "B": map.put("optionB", choiceEntity.getContent());
					if(choiceEntity.getIsTrue().equals("1")) {
						answer+="B";
					}
					break;
					case "C": map.put("optionC", choiceEntity.getContent());
					if(choiceEntity.getIsTrue().equals("1")) {
						answer+="C";
					}
					break;
					case "D": map.put("optionD", choiceEntity.getContent());
					if(choiceEntity.getIsTrue().equals("1")) {
						answer+="D";
					}
					break;
					default : map.put("T", choiceEntity.getContent());
					if(choiceEntity.getIsTrue().equals("1")) {
						answer="T";
					}else {
						answer="F";
					}
					break;
				}
			}
			map.put("answer",answer);
			Json.add(map);
		}
		byte jjson[]=JSONArray.toJSONBytes(Json);
		return jjson;
	}
	public Map<String, Object> appQueryPage() {
		List<PaperEntity> paperEntity=repository.findAll();
		PaperEntity paper=paperEntity.get(randomNum(paperEntity.size(),1).iterator().next());
		JSONArray Json=(JSONArray) JSONArray.parse(paper.getJson());
//		Map map=new HashMap();
//		map.put("paperid", paper.getId());
//		Json.add(map);
		Map<String,Object> m = new HashMap<>();
		m.put("quests", Json);
		m.put("paperId", paper.getId());
		
		return  m;
	}
}
